/**
 * Copyright &copy; 2012-2014 <a href="http://www.iframework.cn">Mas</a> All rights reserved.
 */
package com.iframework.mas.modules.law.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.iframework.mas.common.beanvalidator.BeanValidators;
import com.iframework.mas.common.config.Global;
import com.iframework.mas.common.persistence.Page;
import com.iframework.mas.common.web.BaseController;
import com.iframework.mas.common.utils.DateUtils;
import com.iframework.mas.common.utils.StringUtils;
import com.iframework.mas.common.utils.excel.ExportExcel;
import com.iframework.mas.common.utils.excel.ImportExcel;
import com.iframework.mas.modules.law.entity.Law;
import com.iframework.mas.modules.law.service.LawService;
import com.iframework.mas.modules.sys.entity.User;
import com.iframework.mas.modules.sys.service.SystemService;
import com.iframework.mas.modules.sys.utils.UserUtils;


/**
 * 法律条例Controller
 * @author 余艾龙
 * @version 2016-01-21
 */
@Controller
@RequestMapping(value = "${adminPath}/law/law")
public class LawController extends BaseController {

	@Autowired
	private SystemService systemService;
	
	@Autowired
	private LawService lawService;
	
	@ModelAttribute
	public Law get(@RequestParam(required=false) String id) {
		Law entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = lawService.get(id);
		}
		if (entity == null){
			entity = new Law();
		}
		return entity;
	}
	
	@RequiresPermissions("law:law:view")
	@RequestMapping(value = {"list", ""})
	public String list(Law law, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Law> page = lawService.findPage(new Page<Law>(request, response), law); 
		model.addAttribute("page", page);
		return "modules/law/lawList";
	}

	@RequiresPermissions("law:law:view")
	@RequestMapping(value = "form")
	public String form(Law law, Model model) {
		model.addAttribute("law", law);
		return "modules/law/lawForm";
	}

	@RequiresPermissions("law:law:edit")
	@RequestMapping(value = "save")
	public String save(Law law, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, law)){
			return form(law, model);
		}
		lawService.save(law);
		addMessage(redirectAttributes, "保存法律条例成功");
		return "redirect:"+Global.getAdminPath()+"/law/law/?repage";
	}
	
	@RequiresPermissions("law:law:edit")
	@RequestMapping(value = "delete")
	public String delete(Law law, RedirectAttributes redirectAttributes) {
		lawService.delete(law);
		addMessage(redirectAttributes, "删除法律条例成功");
		return "redirect:"+Global.getAdminPath()+"/law/law/?repage";
	}

	/**
	 * 导出法律条例数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("law:law:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "法律条例数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
    		new ExportExcel("法律条例数据", Law.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出法律条例失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/law/law/?repage";
    }

	/**
	 * 导入法律条例数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("law:law:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Law> list = ei.getDataList(Law.class);
			for (Law law : list){
				try{
//					if ("true".equals(checkLoginName("", user.getLoginName()))){
//						user.setPassword(SystemService.entryptPassword("123456"));
						BeanValidators.validateWithException(validator, law);
//						systemService.saveUser(user);
						lawService.save(law);
						successNum++;
//					}else{
//						failureMsg.append("<br/>法律条例数据: "+law.getDriverlawdetail()+" 已存在; ");
//						failureNum++;
//					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>法律条例数据: "+law.getDriverlawdetail()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>法律条例数据: "+law.getDriverlawdetail()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条法律条例数据，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条法律条例数据"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入法律条例数据失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/law/law/list?repage";
    }
	
	/**
	 * 下载导入法律条例数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("law:law:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "法律条例数据导入模板.xlsx";
    		List<Law> list = Lists.newArrayList(); 
    		Law law=new Law(){};
    		law.setDriverlawdetail("显示文本");
    		law.setDriverlaw("");
    		list.add(law);
    		new ExportExcel("法律条例数据", Law.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/law/law/list?repage";
    }
	
}